//
//  UIViewController+Base.m
//  FashionSpring
//
//  Created by 吕飞俊 on 15/6/3.
//  Copyright (c) 2015年 润媛. All rights reserved.
//

#import "UIViewController+lvfjHelper.h"
#import "MBProgressHUD.h"

#import "UIView+lvfjFrame.h"
#import "StringUtils.h"
#import "UIFont+lvfjHelper.h"

// 屏幕大小
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define TOASTVIEWTAG 10000
#define DEFAULT_TOAST_DURATION 3.0

@interface UIView(lvfjHelper)

- (UIView *)leve1SubViewWithTag:(NSInteger)tag;

@end

@implementation UIView(MyUtil)

- (UIView *)leve1SubViewWithTag:(NSInteger)tag
{
    __block UIView *toastView = nil;
    [[self subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if([(UIView *)obj tag] == tag){
            toastView = (UIView *)obj;
            *stop = YES;
        }
    }];
    return toastView;
}




@end

@implementation UIViewController (Base)

-(void)showBossBuyProgress:(NSString *)text
           backgroundColor:(UIColor *)backgroundColor
                    during:(float)during{
    //显示的
    UIView *myView = self.view;
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:myView];
    hud.color = [UIColor redColor];
    hud.customView.backgroundColor = [UIColor greenColor];
    [myView addSubview:hud];
    hud.mode = MBProgressHUDModeText;
    hud.removeFromSuperViewOnHide = YES;
    [hud show:YES];
    [hud hide:YES afterDelay:during];
}

-(void)showBossBuyImgProgress{
    
    CGRect frame = [self isKindOfClass:[UINavigationController class]]||self.tabBarController?self.view.frame:self.navigationController.view.frame;

    UIView *backV = [[UIView alloc]initWithFrame:frame];
    backV.backgroundColor = [UIColor clearColor];
    
    //图片
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 4, SCREEN_WIDTH * 2 / 3, SCREEN_WIDTH / 4, SCREEN_WIDTH / 4)];
//    imgV.center = self.view.center;
    imgV.image = [UIImage imageNamed:@"progress"];
    [backV addSubview:imgV];
    
    //显示的
    UIView *myView = self.view;
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:myView];
    hud.opacity = 0.0;
    hud.customView.backgroundColor = [UIColor greenColor];
    [myView addSubview:hud];
    hud.customView = backV;
    hud.mode = MBProgressHUDModeCustomView;
    hud.removeFromSuperViewOnHide = YES;
    [hud show:YES];
//    [hud hide:YES afterDelay:0.38];
}

-(void)showBossBuyProgress:(NSString *)text
                       img:(UIImage *)img
                     frame:(CGRect)frame
                    during:(float)during{
    
    UIView *backV = [[UIView alloc]initWithFrame:frame];
    backV.backgroundColor = [UIColor clearColor];
    
    //图片
    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, backV.size.width, backV.size.height)];
    imgV.image = img;
    [backV addSubview:imgV];
    
    //文字
    UILabel *textLb = [[UILabel alloc]init];
    textLb.text = text;
    textLb.textColor = [UIColor redColor];
    textLb.backgroundColor = [UIColor clearColor];
    [textLb sizeToFit];
    textLb.center = imgV.center;
    [imgV addSubview:textLb];
    
    //显示的
    UIView *myView = self.view;
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:myView];
    hud.opacity = 0.0;
    hud.customView.backgroundColor = [UIColor greenColor];
    [myView addSubview:hud];
    hud.customView = backV;
    hud.mode = MBProgressHUDModeCustomView;
    hud.removeFromSuperViewOnHide = YES;
    [hud show:YES];
    [hud hide:YES afterDelay:during];
}

-(void)replaceNavigationViewController:(UIViewController *)ctl{
    NSMutableArray *array = [self.navigationController.viewControllers mutableCopy];
    if (array.count < 2) {
        return;
    }
    [array removeLastObject];
    [array addObject:ctl];
    [self.navigationController setViewControllers:array animated:YES];
}

// 购物车列表
- (void)requestShopingList:(void (^)())block{
//    AHttpRequest *request = [[AHttpRequest alloc] initWithURLString:URL_SHOPPING_LIST];
//    [request setStrTag:@"cart_list"];
//    [request setKey:@"uid" value:[UserData sharedUserData].strUserID];
//    [request setKey:@"token" value:[UserData sharedUserData].strUserToken];
//    
////    [self showProcessCommon];
//    __weak typeof(self) wSelf = self;
//    [request startAsynchronousJSONWithFinished:^(NSDictionary *dic){
//        __strong typeof(wSelf) sSelf = wSelf;
////        [sSelf hideProcessHUD];
//        if ([dic[@"errcode"] integerValue] == 0){
//            NSArray *array = [NSMutableArray arrayWithArray:dic[@"data"][@"items"]];
//            [[UserData sharedUserData] setIntCarNum:array.count];
//            if (block) {
//                block();
//            }
//        }else{
//            [sSelf handleError:dic showAlert:YES];
//        }
//    }failed:^{
//        __strong typeof(wSelf) sSelf = wSelf;
////        [sSelf hideProcessHUD];
//        [sSelf showFailedAlertMsg];
//    }];
}

-(void)handleError:(NSDictionary *)dic showAlertMsg:(NSString *)msg{
//    if ([dic[@"errcode"] integerValue] == ErrorCodeNoLogin) {
////        __weak typeof(self) wSelf = self;
////        [UIAlertView showTitle:dic[@"msg"]
////                       message:nil
////             cancelButtonTitle:@"取消"
////             otherButtonTitles:@[@"登录"]
////                      tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
////                          __strong typeof(wSelf) sSelf = wSelf;
////                          if (buttonIndex != alertView.cancelButtonIndex) {
////                              [sSelf presentLoginctl:self];
////                          }else{
////                              [sSelf.navigationController popViewControllerAnimated:YES];
////                          }
////                      }];
//        [self presentLoginctl:self];
//    }else if ([dic[@"errcode"] integerValue] == ErrorCodeNoSignPersionData){
//        PersionDataViewController * ctl = [[PersionDataViewController alloc]init];
//        ctl.title = @"填写个人资料";
//        ctl.isEditing = YES;
//        [self.navigationController pushViewController:ctl animated:YES];
//    }else if (![StringUtils isEmptyString:msg]){
//        [self showAlertMsg:msg];
//    }
}



-(void)handleError:(NSDictionary *)dic showAlert:(BOOL)show{
    [self handleError:dic showAlertMsg:show?dic[@"msg"]:nil];
}

-(void)loginctlDosth:(UIViewController *)ctl
               block:(void(^)())block{
//    if ([[UserData sharedUserData]isLogin]) {
//        if (block) {
//            block();
//        }
//    }else{
//        [self presentLoginctl:ctl];
//    }
}


-(void)presentLoginctl:(UIViewController *)fromctl{
//    LoginViewController *ctl = [[LoginViewController alloc]init];
//    BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:ctl];
//    nav.navigationBarHidden = YES;
//    [fromctl presentViewController:nav animated:YES completion:^{
//        
//    }];
}

//该方法是为了在登录后执行一些操作
-(void)presentLoginctl:(UIViewController *)fromctl andOperationBlock:(void(^)())block{
//    LoginViewController *ctl = [[LoginViewController alloc]init];
//    ctl.operBlock = block;
//    BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:ctl];
//    nav.navigationBarHidden = YES;
//    [fromctl presentViewController:nav animated:YES completion:^{
//        
//    }];
}

-(UIButton *)ctrateBarButton:(NSString *)title
                         img:(UIImage *)img
                      btSize:(CGSize)size{
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    if (![StringUtils isEmptyString:title]) {
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitle:title forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 0, 60, 15);
    }
    if (img) {
        [button setBackgroundImage:img forState:UIControlStateNormal];
    }
    return button;
}

-(UIButton *)ctrateBarButton:(NSString *)title
                         img:(UIImage *)img{
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25, 25)];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    if (![StringUtils isEmptyString:title]) {
//        button.titleLabel.font = [UIFont ChineseFontWithSize:15];
        [button setTitle:title forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 0, 60, 15);
    }
    if (img) {
        [button setBackgroundImage:img forState:UIControlStateNormal];
    }
    return button;
}

-(void)showFailedAlertMsg{
//    [self showAlertMsg:@"无网络信号，请重新尝试"];
}

-(void)showAlertMsg:(NSString *)msg{
    UIAlertView *alretView = [[UIAlertView alloc]initWithTitle:msg message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alretView show];
}

-(UIButton *)createServerPhoneBt{
    UIButton *button = [self ctrateBarButton:nil img:[UIImage imageNamed:@"Handbag_08.png"]];
    [button addTarget:self action:@selector(callServerPhone) forControlEvents:UIControlEventTouchUpInside];
    return button;
}

//创建打电话功能
-(void)createRightBarButtonToCallServerPhone{
    UIButton *button = [self createServerPhoneBt];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = item;
}

-(void)callServerPhone{
//    [self callPhone:kServicePhoneNo];
}

-(void)callPhone:(NSString *)phoneNo{
//    [UIAlertView showTitle:[NSString stringWithFormat:@"拨打:%@",phoneNo] message:@"" cancelButtonTitle:@"取消 " otherButtonTitles:@[@"确定"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
//        if (buttonIndex != alertView.cancelButtonIndex) {
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNo]]];
//        }    }];
}
//创建并添加到视图--返回到顶部的按钮
-(UIButton *)crateTopBt{
    UIButton *topBt =[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH * 0.8, SCREEN_HEIGHT * 0.7, 40, 40)];
    [topBt setBackgroundImage:[UIImage imageNamed:@"toTop.jpg"] forState:UIControlStateNormal];
    topBt.hidden = YES;
    topBt.backgroundColor = [UIColor clearColor];
    [self.view addSubview:topBt];
    return topBt;
}

-(void)toTop:(UIScrollView *)scrollView{
    [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0) animated:YES];
}

-(void)scrollViewEndScroll:(UIScrollView *)scrollView setTopBtHidden:(UIButton *)bt{
    if (scrollView.contentOffset.y > 480) {
        bt.hidden = NO;
    }else{
        bt.hidden = YES;
    }
}

- (void)showToast:(NSString *)toast
{
    [self showToast:toast inWindow:YES];
}

- (void)showToast:(NSString *)toast inWindow:(BOOL)inWindos
{
//    [self showToast:toast duration:0.58 inWindow:inWindos];
}

- (void)showToast:(NSString *)toast duration:(CGFloat)dur
{
//    [self showToast:toast duration:dur inWindow:YES];
//    [self showToast:toast duration:dur completionBlack:nil];
}

//- (void)showToast:(NSString *)toast duration:(CGFloat)dur completionBlack:(void (^)(void))completion
//{
//    [self showToast:toast duration:dur completionBlack:completion];
//}

+ (UIView *)getLeve1SubViewWithParentView:(UIView *)parentView tag:(NSInteger)tag
{
    __block UIView *toastView = nil;
    [[parentView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if([(UIView *)obj tag] == tag){
            toastView = (UIView *)obj;
            *stop = YES;
        }
    }];
    return toastView;
}

//
- (void)showProcessHUD:(NSString *)text
{
    if ([self isKindOfClass:[UINavigationController class]]||self.tabBarController) {
        [MBProgressHUD showHUDAddedTo:self.view text:text animated:YES];
    }
    else if(self.navigationController){
        [MBProgressHUD showHUDAddedTo:self.navigationController.view text:text animated:YES];
    }
}

-(void)showProcessCommon{
//    [self showProcessHUD:@"BossBuy"];
    [self showBossBuyImgProgress];
}

- (void)hideProcessHUD
{
    //隐藏self.view的HUD
    NSArray *HUDArr1 = [MBProgressHUD allHUDsForView:self.view];
    if (HUDArr1.count != 0) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }
    //隐藏self.navigationController.view的HUD
    NSArray *HUDArr2 = [MBProgressHUD allHUDsForView:self.navigationController.view];
    if (HUDArr2.count != 0) {
        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    }
    
    /*PS:可能需要扩展隐藏其他View的HUD*/
    
    //    if ([self isKindOfClass:[UINavigationController class]]) {
    //        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    //    }
    //    else if(self.navigationController){
    //        [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
    //    }
}


@end
